package com.yhp.web.userweb;

import com.mysql.cj.PreparedQuery;
import com.yhp.bo.CenterUserBO;
import com.yhp.bo.UsersBO;
import com.yhp.pojo.Users;
import com.yhp.resource.FileUpad;
import com.yhp.service.userservice.CenterUserService;
import com.yhp.utils.CookieUtils;
import com.yhp.utils.DateUtil;
import com.yhp.utils.JSONResult;
import com.yhp.utils.JsonUtils;
import com.yhp.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "用户信息接口",tags = {"用户信息相关接口"})
@RestController
@RequestMapping("/userInfo")
public class UserCenterController extends BaseController {
    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FileUpad fileUpad;


    //更新用户信息
    @ApiOperation(value = "更新用户信息",notes = "更新用户信息",httpMethod = "POST")
    @PostMapping("/update")
    public JSONResult updateUserInfo(
            @ApiParam(name = "userId",value = "用户id",required = true)
                    String userId,
            @RequestBody @Valid CenterUserBO centerUserBO, //表示要验证
            BindingResult result,//hibernate-validate 验证的错误信息
            HttpServletRequest request, HttpServletResponse response){

        //判断BindingResult是否保存错误的验证信息，如果有，则直接return
        if(result.hasErrors()){
            Map<String, String> errors = getErrors(result);
            return JSONResult.errorMap(errors);
        }


        Users users = centerUserService.updateUserInfo(userId, centerUserBO);

        setNullProperties(users);
        //更新cookie的信息
        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(users),true);
        //TODO 后续会修改，增加令牌token,会整合redis,分布式会话

        return JSONResult.ok();
    }


    private Map<String,String> getErrors(BindingResult result){
        Map map=new HashMap();
        List<FieldError> fieldErrors = result.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();//发生错误的属性
            String defaultMessage = fieldError.getDefaultMessage();//错误信息
            map.put(field,defaultMessage);
        }
        return map;
    }

    private Users setNullProperties(Users users){
        users.setPassword(null);
        users.setRealname(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setBirthday(null);
        return users;
    }

    //修改头像
    @ApiOperation(value = "修改头像",notes = "修改头像",httpMethod = "POST")
    @PostMapping("/uploadFace")
    public JSONResult changImg(
            @ApiParam(name = "userId",value = "用户id",required = true)
            String userId,
            @ApiParam(name = "file",value = "头像文件",required = true)
            MultipartFile file,
            HttpServletRequest request, HttpServletResponse response){
        //定义头像保存地址
        //String filePath=IMAGE_HEADFACE_URL;
        String filePath=fileUpad.getImage_headface_url();//使用属性文件替代静态属性
        //在路径上为每一个用户增加一个userid,用于区分不同用户上传
        String uploadPathPrefix= File.separator+userId;
        FileOutputStream fileOutputStream =null;
        String fileName=null;
        String finalPath=null;
        if (file != null) {
            try {
                //获得上传的文件名
                String originalFilename = file.getOriginalFilename();
                if(StringUtils.isBlank(originalFilename)){
                    return  JSONResult.errorMsg("文件名不允许为空");
                }
                //文件重命名
                String[] strings = originalFilename.split("\\.");
                //获取文件的后缀名
                String suffix = strings[strings.length - 1];
                //文件名重组，有两种方案 1.覆盖式  2.增量式:在原有基础上拼接当前时间
                //图片后缀限制，防止走后门
                if(!suffix.equalsIgnoreCase("png")&&
                        !suffix.equalsIgnoreCase("jpg")&&
                        !suffix.equalsIgnoreCase("jpeg")){
                    return JSONResult.errorMsg("图片格式不正确");
                }


                fileName="face-"+userId+"."+suffix;

                //头像的最终保存位置
                finalPath=filePath+uploadPathPrefix+File.separator+fileName;
                //用于提供给web服务访问的地址
                uploadPathPrefix+=("/"+fileName);

                //保存
                File outFile = new File(finalPath);
                if(outFile.getParentFile()!=null){
                    //创建文件夹
                    outFile.getParentFile().mkdirs();
                }

                //文件输出保存到目录
                fileOutputStream = new FileOutputStream(outFile);
                InputStream inputStream = file.getInputStream();
                IOUtils.copy(inputStream,fileOutputStream);

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else{
            return  JSONResult.errorMsg("文件不允许为空");
        }

        //更新用户头像到数据库
        //由于浏览器可能存在缓存问题，所以在这里需要添加时间戳来保证更新后的图片可以及时刷新
        String imageServerUrl=fileUpad.getImage_server_url()+uploadPathPrefix+"?t="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        Users users = centerUserService.updateUserFace(userId, imageServerUrl);

        //更新cookie
        setNullProperties(users);
        //更新cookie的信息
        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(users),true);
        //TODO 后续会修改，增加令牌token,会整合redis,分布式会话

        return JSONResult.ok();
    }

}
